package com.tcm.content.service.impl;

import cn.hutool.core.date.DateUtil;
import com.base.core.dozer.DozerConvert;
import com.base.core.exception.ServiceException;
import com.base.core.utils.R;
import com.base.genid.generator.UidGenerator;
import com.base.redis.JedisClient;
import com.tcm.content.dao.mapper.PanelMapper;
import com.tcm.content.dto.PanelDTO;
import com.tcm.content.entity.Panel;
import com.tcm.content.enums.BusinessCodeEnum;
import com.tcm.content.service.PanelService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import java.util.List;

@DubboService
public class PanelServiceImpl implements PanelService {

    private final static Logger log = LoggerFactory.getLogger(PanelServiceImpl.class);

    @Autowired
    private PanelMapper tbPanelMapper;
    @Autowired
    private JedisClient jedisClient;

    @DubboReference(version = "0.0.1-beta", group = "cached-uid", timeout = 6000, check = false, retries = 3)
    private UidGenerator uidGenerator;

    @Override
    public PanelDTO findById(Long id) {
        Panel tbPanel = tbPanelMapper.findById(id);
        if (tbPanel == null) {
            R.throwFail(BusinessCodeEnum.QUERY_FAIL_BY_ID);
        }
        PanelDTO pane = new PanelDTO();
        BeanUtils.copyProperties(tbPanel, pane);
        return pane;
    }

    @Override
    public List<PanelDTO> listPanel(int position, boolean showAll) {

        List<Panel> panelList = tbPanelMapper.listPanelByPosition(position);
        return DozerConvert.copyList(panelList, PanelDTO.class);
    }

    @Override
    public int addPanel(PanelDTO panel) throws ServiceException  {

        Panel tbPanel = new Panel();
        BeanUtils.copyProperties(panel, tbPanel);
        tbPanel.setCreated(DateUtil.date());
        tbPanel.setUpdated(DateUtil.date());
        tbPanel.setId(uidGenerator.getUID());
        tbPanel.setStatus(1);
        if (tbPanelMapper.insert(tbPanel) != 1) {
            R.throwFail(BusinessCodeEnum.PANEL_ADD_FAIL);
        }
        //同步缓存
        return 1;
    }

    @Override
    public int updatePanel(PanelDTO panel) throws ServiceException {
        PanelDTO old = findById(panel.getId());
        Panel tbPanel = new Panel();
        BeanUtils.copyProperties(panel, tbPanel);
        tbPanel.setUpdated(DateUtil.date());
        if (tbPanelMapper.update(tbPanel) != 1) {
            R.throwFail("更新板块失败");
        }
        //同步缓存
        return 1;
    }

    @Override
    public int deletePanel(Long id) {
        if (tbPanelMapper.delete(id) != 1) {
            R.throwFail("删除内容分类失败");
        }
        //同步缓存
        return 1;
    }

}
